package org.zhxy.zhxy.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

import lombok.val;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zhxy.zhxy.entity.Admin;
import org.zhxy.zhxy.entity.User;
import org.zhxy.zhxy.utils.AdminHolder;
import org.zhxy.zhxy.utils.RedisConstants;
import org.zhxy.zhxy.utils.UserHolder;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token刷新拦截器
 */

@Component
public class ReFreshInterceptor implements HandlerInterceptor {

    /**
     * 注入redis模板
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 刷新token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String method = request.getMethod();
        System.out.println(method);
      if ("OPTIONS".equals(method)){
          return true;
      }

        //1.获取请求中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            //放行
            return true;
        }

        //2.基于token获取redis中的的用户
        Map<Object, Object> userMap = stringRedisTemplate.
                opsForHash().entries(RedisConstants.LOGIN_TOKEN + token);

        //3.判断用户是否存在
        if (userMap.isEmpty()){
            //不存在放行
            return true;
        }


        String requestURI = request.getRequestURI();
        if(request.getRequestURI().contains("/admin")){
            // 管理端请求
            //4.将查询到的Hash转换为Admin对象
            Admin admin = BeanUtil.fillBeanWithMap(userMap, new Admin(), false);
            //5.存在，保存管理员信息到ThreadLocal
            AdminHolder.saveAdmin(admin);
        }else{
            // 小程序请求
            //4.将查询到的Hash转换为User对象
            User user = BeanUtil.fillBeanWithMap(userMap, new User(), false);
            //5.存在，保存用户信息到ThreadLocal
            UserHolder.saveUser(user);
        }

        //6.刷新token有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_TOKEN + token, RedisConstants.LOGIN_TOKEN_TTL, TimeUnit.HOURS);

        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeAdmin();
        UserHolder.removeUser();
    }
}
















